package io.nutz.nutzsite.module.exam.controller;

import io.nutz.nutzsite.common.base.Result;
import io.nutz.nutzsite.common.utils.DateUtils;
import io.nutz.nutzsite.common.utils.ShiroUtils;
import io.nutz.nutzsite.common.utils.excel.ExcelUtil;
import io.nutz.nutzsite.common.utils.excel.ExportExcel;
import io.nutz.nutzsite.module.exam.models.Qdb;
import io.nutz.nutzsite.module.exam.models.Qtype;
import io.nutz.nutzsite.module.exam.models.Question;
import io.nutz.nutzsite.module.exam.services.QdbService;
import io.nutz.nutzsite.module.exam.services.QtypeService;
import io.nutz.nutzsite.module.exam.services.QuestionService;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import org.nutz.plugins.slog.annotation.Slog;
/**
 * 题目 信息操作处理
 * 
 * @author lrw
 * @date 2020-04-08
 */
@IocBean
@At("/exam/question")
public class QuestionController {
	private static final Log log = Logs.get();

	@Inject
	private QuestionService questionService;
	@Inject
	private QtypeService qtypeService;
	@Inject
	private QdbService qdbService;
	
	@RequiresPermissions("exam:question:view")
	@At("")
	@Ok("th:/exam/question/question.html")
	public void index(HttpServletRequest req) {
		List<Qtype> list=qtypeService.query();
		req.setAttribute("qtypes", list);
		Qdb qdb=new Qdb();
		qdb.setId(1);
		qdb.setName("选择题库/知识点");
		req.setAttribute("qdb",qdb);
	}

	/**
	 * 查询题目列表
	 */
	@RequiresPermissions("exam:question:list")
	@At
	@Ok("json")
	public Object list(@Param("pageNum")int pageNum,
					   @Param("pageSize")int pageSize,
					   @Param("name") String name,
					   @Param("id") Integer id,
					   @Param("kbid") Integer kbid,
					   //@Param("qdbid") Integer qdbid,
					   @Param("qtid") Integer qtid,
					   @Param("orderByColumn") String orderByColumn,
					   @Param("isAsc") String isAsc,
					   HttpServletRequest req) {
		Cnd cnd = Cnd.NEW();
		if(id!=null){
			cnd.and("id","=", id);
		}else{
			if (!Strings.isBlank(name)){
				cnd.and("name", "like", "%" + name +"%");
			}			
			if(kbid!=null){
				SqlExpressionGroup e1 = Cnd.exps("kbid","=", kbid).or("qdbid","=", kbid);
				cnd.and(e1);
			}
			if(qtid!=null){
				cnd.and("qtid","=", qtid);
			}
		}
		return questionService.tableList(pageNum,pageSize,cnd,orderByColumn,isAsc,null);
	}

	/**
	 * 新增题目
	 */
	@At("/add")
	@Ok("th:/exam/question/add.html")
	public void add( HttpServletRequest req) {
		List<Qtype> list=qtypeService.query();
		req.setAttribute("qtypes", list);
		Qdb qdb=new Qdb();
		qdb.setPid(1);
		qdb.setName("选择题库/知识点");
		req.setAttribute("qdb",qdb);
	}

	/**
	 * 新增保存题目
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("exam:question:add")
	@Slog(tag="题目", after="新增保存题目 id=${args[0].id}")
	public Object addDo(@Param("..") Question question,HttpServletRequest req) {
		try {
			question.setName(new String(new Base64().decode(question.getName()), "UTF-8"));
			question.setAnsA(new String(new Base64().decode(question.getAnsA()), "UTF-8"));
			question.setAnsB(new String(new Base64().decode(question.getAnsB()), "UTF-8"));
			if(Strings.isNotBlank(question.getAnsC()))
			question.setAnsC(new String(new Base64().decode(question.getAnsC()), "UTF-8"));
			if(Strings.isNotBlank(question.getAnsD()))
			question.setAnsD(new String(new Base64().decode(question.getAnsD()), "UTF-8"));
			if(Strings.isNotBlank(question.getQnote()))
			question.setQnote(new String(new Base64().decode(question.getQnote()), "UTF-8"));
			question.setCreateBy(ShiroUtils.getSysUserId());
			question.setCreateTime(new Date());
			
			questionService.insert(question);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 修改题目
	 */
	@At("/edit/?")
	@Ok("th:/exam/question/edit.html")
	public void edit(int id, HttpServletRequest req) {
		Question question = questionService.fetch(id);
		req.setAttribute("question",question);
		id=question.getKbid();Qdb qdb=null;
		if(id!=0) qdb = qdbService.fetch(id);
		if(qdb==null)qdb = qdbService.fetch(question.getQdbid());
		req.setAttribute("qdb",qdb);
		List<Qtype> list=qtypeService.query();
		req.setAttribute("qtypes", list);
	}

    /**
     * 详情题目
     */
    @At("/detail/?")
    @Ok("th:/exam/question/detail.html")
    public void detail(int id, HttpServletRequest req) {
		Question question = questionService.fetch(id);
		questionService.fetchLinks(question, "qdb|qtype");
        req.setAttribute("question",question);
    }

    /**
	 * 修改保存题目
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("exam:question:edit")
	@Slog(tag="题目", after="修改保存题目")
	public Object editDo(@Param("..") Question question,HttpServletRequest req) {
		try {
			question.setName(new String(new Base64().decode(question.getName()), "UTF-8"));
			question.setAnsA(new String(new Base64().decode(question.getAnsA()), "UTF-8"));
			question.setAnsB(new String(new Base64().decode(question.getAnsB()), "UTF-8"));
			if(Strings.isNotBlank(question.getAnsC()))
			question.setAnsC(new String(new Base64().decode(question.getAnsC()), "UTF-8"));
			if(Strings.isNotBlank(question.getAnsD()))
			question.setAnsD(new String(new Base64().decode(question.getAnsD()), "UTF-8"));
			if(Strings.isNotBlank(question.getQnote()))
			question.setQnote(new String(new Base64().decode(question.getQnote()), "UTF-8"));

			if(Lang.isNotEmpty(question)){
				question.setUpdateBy(ShiroUtils.getSysUserId());
				question.setUpdateTime(new Date());
				questionService.update(question);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 删除题目
	 */
	@At("/remove")
	@Ok("json")
	@RequiresPermissions("exam:question:remove")
	@Slog(tag ="题目", after= "删除题目:${array2str(args[0])}")
	public Object remove(@Param("ids")String[] ids, HttpServletRequest req) {
		try {
			questionService.delete(ids);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

    @At
	@Ok("json")
    public Object export(@Param("name") String name,
			   @Param("id") Integer id,
			   @Param("kbid") Integer kbid,
			   @Param("qtid") Integer qtid,
			   HttpServletRequest req, HttpServletResponse response) {
    	Cnd cnd = Cnd.NEW();
		if(id!=null){
			cnd.and("id","=", id);
		}else{
			if (!Strings.isBlank(name)){
				cnd.and("name", "like", "%" + name +"%");
			}			
			if(kbid!=null){
				SqlExpressionGroup e1 = Cnd.exps("kbid","=", kbid).or("qdbid","=", kbid);
				cnd.and(e1);
			}
			if(qtid!=null){
				cnd.and("qtid","=", qtid);
			}
		}
    	List<Question> list = questionService.query(cnd);
		String fileName = "客观题数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try{
			new ExportExcel("客观题数据", Question.class).setDataList(list).writeFile(fileName);
		}catch(Exception ex)
		{
			log.error(ex.getMessage());
			return Result.error("导出失败"+ex.getMessage());
		}
		return Result.success(fileName);
    }
    @At
	@Ok("json")
	public Object export2(HttpServletRequest req, HttpServletResponse resp){
		//String fileName = "系统参数"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
		List<Question> list =questionService.query();
		log.debug("\r\nex2:"+list.size()+"\r\n");
		ExcelUtil<Question> util = new ExcelUtil<Question>(Question.class);
        return util.exportExcel(list, "客观题数据");

	}
	/**
	 * 下载导入数据模板
	 */
	@RequiresPermissions("exam:question:importTemplate")
	@At
	@Ok("json")
	public Object importTemplate(HttpServletResponse response) {
		List<Question> list = questionService.query(Cnd.where("id","=","7455"));
		String fileName = "客观题模板数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try{
			new ExportExcel("客观题模板数据", Question.class).setDataList(list).writeFile(fileName);
		}catch(Exception ex)
		{
			log.error(ex.getMessage());
			return Result.error("导出失败"+ex.getMessage());
		}
		return Result.success(fileName);
	}

	/**
	 * 导入数据
	 */
	@AdaptBy(type = UploadAdaptor.class, args = {"ioc:fileUpload"})
    @POST
	@RequiresPermissions("exam:question:import")
	@At
	@Ok("json")
	public Object importData(@Param("file") TempFile file,@Param("updateSupport")  String updateSupport) {
		try {
			//boolean isUpdateSupport = updateSupport=="true"?true:false;
			String message = questionService.importData(file);
			return Result.success(message);
		} catch (Exception ex) {
			return Result.error(ex.getMessage());
		}
	}
}
